const path = require('path');
const fs = require('fs');

// 环境变量验证
const requiredEnvVars = [];

const optionalEnvVars = {
  NODE_ENV: 'development',
  PORT: '7932',
  LOG_LEVEL: 'info',
  CORS_ORIGIN: '*',
  RATE_LIMIT_WINDOW: '60000',
  RATE_LIMIT_MAX: '100',
  MONGODB_URI: 'mongodb://localhost/hallochat'
};

// 验证必需的环境变量
function validateEnv() {
  const missing = requiredEnvVars.filter(envVar => !process.env[envVar]);
  if (missing.length > 0) {
    throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
  }
}

// 加载配置文件
function loadConfig() {
  const configPath = path.join(__dirname, '..', 'config.json');
  let config = {};
  
  try {
    if (fs.existsSync(configPath)) {
      config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    }
  } catch (error) {
    console.warn('Could not load config.json, using defaults');
  }

  return {
    server: {
      port: parseInt(process.env.PORT || config.port || 7932),
      env: process.env.NODE_ENV || 'development',
      cors: {
        origin: process.env.CORS_ORIGIN || config.cors?.origin || '*',
        methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
        allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
      }
    },
    database: {
      uri: process.env.MONGODB_URI || config.database?.uri || 'mongodb://localhost/hallochat',
      options: {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        maxPoolSize: 10,
        serverSelectionTimeoutMS: 5000,
        socketTimeoutMS: 45000,
        ...config.database?.options
      }
    },
    security: {
      jwtSecret: process.env.JWT_SECRET || process.env.JWT_ACCESS_SECRET || config.security?.jwtSecret || 'default_jwt_secret_32_characters_long',
      tokenExpiration: process.env.TOKEN_EXPIRATION || process.env.JWT_ACCESS_EXPIRES_IN || config.security?.tokenExpiration || '24h',
      bcryptRounds: 12
    },
    logging: {
      level: process.env.LOG_LEVEL || config.logging?.level || 'info',
      file: process.env.LOG_FILE || config.logging?.file || 'logs/server.log',
      maxFiles: 5,
      maxSize: '10m'
    },
    rateLimit: {
      windowMs: parseInt(process.env.RATE_LIMIT_WINDOW || config.rateLimiting?.windowMs || 60000),
      max: parseInt(process.env.RATE_LIMIT_MAX || config.rateLimiting?.max || 100),
      message: 'Too many requests from this IP, please try again later.'
    },
    mdns: {
      enabled: process.env.MDNS_ENABLED !== 'false' && (config.mdns?.enabled ?? true),
      serviceName: process.env.MDNS_SERVICE_NAME || config.mdns?.serviceName || 'hallo-chat',
      displayName: process.env.MDNS_DISPLAY_NAME || config.mdns?.displayName || 'Hallo Chat Server'
    },
    ssl: {
      enabled: process.env.SSL_ENABLED === 'true' || config.ssl?.enabled || false,
      certPath: process.env.SSL_CERT_PATH || config.ssl?.certPath || './ssl/cert.pem',
      keyPath: process.env.SSL_KEY_PATH || config.ssl?.keyPath || './ssl/key.pem'
    }
  };
}

// 配置验证
function validateConfig(config) {
  const errors = [];

  if (!config.security.jwtSecret) {
    errors.push('JWT_SECRET or JWT_ACCESS_SECRET is required');
  } else if (config.security.jwtSecret !== 'default_jwt_secret_32_characters_long' && config.security.jwtSecret.length < 32) {
    errors.push('JWT_SECRET must be at least 32 characters long');
  }

  if (config.server.port < 1 || config.server.port > 65535) {
    errors.push('PORT must be between 1 and 65535');
  }

  if (config.rateLimit.max < 1) {
    errors.push('RATE_LIMIT_MAX must be greater than 0');
  }

  if (errors.length > 0) {
    throw new Error(`Configuration validation failed: ${errors.join(', ')}`);
  }
}

// 初始化配置
function initConfig() {
  validateEnv();
  const config = loadConfig();
  validateConfig(config);
  return config;
}

module.exports = {
  config: initConfig(),
  validateEnv,
  loadConfig,
  validateConfig
};